#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>

int main(){
  //1.先创建一个匿名管道文件
  int fd[2];
  if(pipe(fd)<0){
    perror("pipe error!\n");
    exit(1);
  }

  //2.创建子进程获取父进程的文件描述符表
  pid_t id = fork();
  if(id < 0){
    perror("fork error!\n");
  }
  else if(id == 0){
    //子进程向管道文件中写数据,将读端关闭
    close(fd[0]);
    char* str = "child send message to father!";
    int count = 0;
    while(count<5){
      ssize_t ret =   write(fd[1],str,strlen(str));
      sleep(1);
      ++count;
    }

    close(fd[1]);
    exit(0);
  }

  else{
    //父进程向管道文件中读数据，将写段关闭
    close(fd[1]);
    char buf[128];
    while(1){
      ssize_t ret = read(fd[0],buf,sizeof(buf));
      if(ret > 0){
        buf[ret] = '\0';
        printf("father recive message,the message is:%s\n",buf);
      }
      else{
        printf("child write finish!\n");
        break;
      }
    }

    //3.获取子进程退出码
    int status = 0;
    if(waitpid(id,&status,WNOHANG)>0){
      printf("father wait success!\n");
    }
    close(fd[0]);
  }

  return 0;
}
